import { useState, useEffect } from 'react';
import { Subject, Subscription } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

import Taro, { FC, useRouter } from '@tarojs/taro'
import { AtInput, AtForm } from 'taro-ui'
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/checkbox.scss";
import { View, Text, Button } from '@tarojs/components'

import { SignInContentReq } from '@/models/request/roomReq';
import storage from '@/utils/storage';

import "taro-ui/dist/style/components/button.scss" // 按需引入 
import './index.scss'
import { useRoomFacade } from './useRoomFacade';

//签到
export const SignIn: FC = () => {

  const [roomFacade] = useRoomFacade();
  const router = useRouter();
  const roomId = router.params.roomId || '';
  // const [signInData, setSignInData] = useState([] as SignInContentReq[])
  const [signInData, setSignInData]: any = useState([])
  const [select, setSelect]: any = useState([])
  const [signedIn, setSignedIn] = useState(false)
  const [checkSave, setCheckSave] = useState(false)
  const [liveType, setLiveType] = useState(Number(router.params.liveType)) //直播类型
  // 初始化按钮接收参数subject，所有按钮或者操作都可以通过这个emmiter触发
  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject)

  // 输入框需要change事件
  const handleChange1 = (index, value) => {
    signInData[index].content = value;
    console.log(signInData[index]);
    setSignInData(JSON.parse(JSON.stringify(signInData)))
  }

  const goBackRoom = () => {
    if (liveType === 0) {
      Taro.navigateTo({
        url: `/pages/liveRoom/graphicLive/index?roomId=${roomId}`
      })
    } else {
      Taro.navigateTo({
        url: `/pages/liveRoom/room/index?roomId=${roomId}`
      })
    }

  }

  // 保存信息按钮
  // const handleChange = (value) => {
  //   console.log(value,);
  //   if (value.includes(true)) {
  //     setCheckSave(true)
  //     console.log('是否有触发true');

  //   } else {
  //     setCheckSave(false)
  //     console.log('是否有触发false');
  //   }
  // Taro.setStorage({
  //   key: 'flagToSave',
  //   data: checkSave
  // })
  //   setSelect(value)
  // }

  const checkboxOption = [
    {
      value: true,
      label: '保存签到信息后续自动填写',
    }
  ]

  // 保存签到
  useEffect(() => {
    const subscriptions: Subscription[] = [
      emitter.asObservable()
        .pipe(
          map(objs => objs as SignInContentReq[]),
          switchMap(list => {
            list.map(i => {
              if (i.required && i.content === '') {
                throw Taro.showToast({
                  title: `请输入${i.title}`,
                  icon: 'none',
                  duration: 2000
                })
              }
            })

            storage.put('signInData', list, 7 * 24 * 3600);
            return roomFacade.UserSignIn(roomId, list)
          })
        )
        .subscribe(
          () => {
            const Data = storage.get('signIned') || [];
            Data.map((data, index) => {

              if (data.roomId === roomId) {
                data = Object.assign(data, { signIned: true })
                Data.splice(index, 1, data)
              } else {
                data = { roomId: roomId, signIned: true }
              }
            })
            //写签到状态的缓存,缓存一星期
            storage.put(roomId, Data, 7 * 24 * 3600);

            Taro.showToast({
              icon: 'none',
              title: '签到成功',
              duration: 2000,
            });
            setTimeout(() => {
              if (liveType === 0) {
                Taro.navigateTo({
                  url: `/pages/liveRoom/graphicLive/index?roomId=${roomId}`
                })
              } else {
                Taro.navigateTo({
                  url: `/pages/liveRoom/room/index?roomId=${roomId}`
                })
              }
            }, 2000)
            // 签到成功则修改存储的状态
            const flag = storage.get(roomId)
            flag.signIned = true

            //写签到状态的缓存,缓存一星期
            storage.put(roomId, flag, 7 * 24 * 3600);

          },
          () => {
            setEmitter(initSubject);
          }
        )
    ]
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter])

  // 获取直播间的签到设置
  useEffect(() => {
    const subscriptions: Subscription[] = [
      // 获取签到设置
      roomFacade.getSignInFrom()
        .subscribe(
          (res) => {
            const newArr: SignInContentReq[] = res.map((item: SignInContentReq) => { item.content = ''; return item })
            const data = storage.get('signInData')
            console.log(data, '同步');
            if (data && data.length > 0) {
              newArr.map(item => {
                data.map(i => {
                  if (item.property === i.property) {
                    item.content = i.content
                  }
                })
                return item
              })
            }
            setSignInData(JSON.parse(JSON.stringify(newArr)))
            // let flag = Taro.getStorageSync('flagToSave')
            // if (flag) {
            // setSelect([checkboxOption[0].value])
            // }
          }),

      roomFacade.getUserSignInfo(roomId)
        .subscribe(
          (res) => {
            if (res.signInContent && res.signInContent.length > 0) {
              setSignedIn(true)
              setSignInData(JSON.parse(JSON.stringify(res.signInContent)))
            }
          }
        )
    ]
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [])



  return (
    <View className='index'>
      {!signedIn && (
        <View className='main'>
          <AtForm>
            {signInData.map((item, index) => {
              return (
                <AtInput key={String(index)}
                  required={item.required}
                  name={item.property}
                  title={item.title}
                  type='text'
                  placeholder={'请输入' + item.title}
                  value={item.content}
                  onChange={handleChange1.bind(this, index)}
                  className='text'
                >
                  <View className='right-text'>
                    <Text className={item.content.length > 20 ? 'text-style' : ''}>{item.content ? item.content.length : 0}/20</Text>
                  </View>
                </AtInput>
              )
            }
            )}
            {/* <AtCheckbox
            className='check'
            options={checkboxOption}
            selectedList={select}
            onChange={handleChange.bind(this)}
          /> */}
          </AtForm>

          <Button className='button' onClick={() => emitter.next(signInData)}>
            <Text className='text'>立刻签到</Text>
          </Button>
        </View>
      )}

      {signedIn && (
        <View className='main'>
          <AtForm>
            {signInData.map((item, index) => {
              return (
                <AtInput key={index}
                  name={item.property}
                  title={item.title}
                  type='text'
                  value={item.content}
                  onChange={handleChange1.bind(this, index)}
                  className='text'
                  editable={false}
                >
                  <View className='right-text'>
                    <Text className={item.content.length > 20 ? 'text-style' : ''}>{item.content ? item.content.length : 0}/20</Text>
                  </View>
                </AtInput>
              )
            }
            )}
          </AtForm>
          <View className='goback-room' onClick={goBackRoom}><Text>返回直播间</Text></View>
        </View>
      )}
    </View >

  )
}
export default SignIn